﻿using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using XLZF.MicroServices.Models;

namespace XLZF.MicroServices.Common;

/// <summary>
/// 
/// </summary>
public class JwtHelper
{
    private readonly IConfiguration _configuration;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="configuration"></param>
    public JwtHelper(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    /// <summary>
    /// 创建令牌
    /// </summary>
    /// <param name="_Users"></param>
    /// <returns></returns>
    public string CreateToken(Clothing_Users _Users)
    {
        // 1. 定义需要使用到的Claims
        var claims = new[]
        {
        new Claim(ClaimTypes.NameIdentifier,_Users.UserID.ToString()),
        new Claim(ClaimTypes.Name, _Users.UserName), //HttpContext.User.Identity.Name
        new Claim(ClaimTypes.Role, "admin"), //HttpContext.User.IsInRole("r\_admin")
        //new Claim(JwtRegisteredClaimNames.Jti, "admin"),
        new Claim("LoginName",_Users.LoginName),
        //new Claim("UserName", _Users.UserName),
        //new Claim("Name", "超级管理员"),
    };

        // 2. 从 appsettings.json 中读取SecretKey
        var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

        // 3. 选择加密算法
        var algorithm = SecurityAlgorithms.HmacSha256;

        // 4. 生成Credentials
        var signingCredentials = new SigningCredentials(secretKey, algorithm);

        // 5. 根据以上，生成token
        var jwtSecurityToken = new JwtSecurityToken(
            _configuration["Jwt:Issuer"],     //Issuer
            _configuration["Jwt:Audience"],   //Audience
            claims,                          //Claims,
            DateTime.Now,                    //notBefore
            DateTime.Now.AddSeconds(3000),    //expires
            signingCredentials               //Credentials
        );

        // 6. 将token变为string
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return token;
    }
}
